<!-- 订单中心 -->
<template>
	<view class="container">
		<!--    <global-loading />-->
		<view style="padding-bottom:68upx;">
			<u-sticky bg-color="#fff">
				<u-tabs class="tabs" disabled :list="tabList" :is-scroll="false" active-color="#C5AA7B"
					:current="tabCurrentType" @change="handleTabChange" />
			</u-sticky>
			<view class="order-list-box u-skeleton">
				<Skeleton el-color="#efefef" bg-color="#fff" :loading="loading" :animation="true" />
				<view class="item ske-loading" v-for="(orderItem, orderIndex) in list" :key="orderIndex">
					<view class="order-info-box" @click="goOrderDesc(orderItem)">
						<view class="order-info">
							<lable v-if="out">{{orderItem.createTime}}
								转赠给用户{{orderItem.toPhone}}{{orderItem.amount}}个{{coinName}}</lable>
							<lable v-else>来自用户{{orderItem.fromPhone}}转赠的{{orderItem.amount}}个{{coinName}}</lable>

							<lable v-if="orderItem.confirmState!=0">{{getOrderStatusLabel(orderItem.confirmState)}}
							</lable>
							<lable v-if="out">{{orderItem.bak}}</lable>
						</view>
						<view class="btnBox flex-items flexSpBetween"
							:class="{flexSpBetween: orderItem.state===5 || orderItem.state === 9}">
							<view class="u-skeleton-rect" style="min-height: 60rpx; min-width: 60rpx;">
								<view class="delIcon" v-if="orderItem.state===5 || orderItem.state === 9"
									@click.stop="handleDeleteOrder(orderItem)"></view>
							</view>
							<view class="order-btn-box u-skeleton-rect">
								<text :class="['btn',buttonItem.className] "
									v-for="buttonItem in getOrderOptionButtonObj(orderItem)" :key="buttonItem.name"
									@click.stop="handleOrderOptionButtonEvent(buttonItem)">
									{{ buttonItem.name }}
								</text>
							</view>
						</view>
					</view>
				</view>
				<slide-loading />
				<view class="reachBottom" v-if="topLeft > 300 && !isEmpty && list.length >=listTotal">
					<image class="reach-icon" :src="`${VUE_APP_STATIC_URL}static/img/reachBottom.png`" mode="widthFix">
					</image>
					<text class="reach-text">这里到底了哦~~</text>
				</view>
				<Empty background="none" :show="isEmpty"
					:icon-url="`${VUE_APP_STATIC_URL}static/images/emptyOrderImg.png`">您还没有记录哦~
				</Empty>
			</view>
		</view>
		<!-- 回到顶部 -->
		<ReturnTop :returnTopFlag="returnTopFlag" />
	</view>
</template>

<script setup>
	import Empty from "../../components/Empty";
	import {
		handleDoPay
	} from "@/utils/payUtil";
	import Skeleton from "../../components/Skeleton";
	import {
		request
	} from '@/utils/request'
	import API from "../../config/api";
	import {
		inject,
		nextTick,
		onMounted,
		ref
	} from "vue";
	import {
		onBackPress,
		onLoad,
		onPageScroll,
		onReachBottom,
		onShow,
		onUnload
	} from "@dcloudio/uni-app";
	import {
		useLoading
	} from "@/hooks/useLoading";
	const {
		showLoading,
		hideLoading
	} = useLoading();
	import {
		VUE_APP_STATIC_URL
	} from "@/config/api";
	import SlideLoading from "../../components/SlideLoading/index.vue";

	const returnTopFlag = ref(false); // 回到顶部
	const topLeft = ref(0)
	const $showLoading = showLoading
	const $hideLoading = hideLoading
	const $jump = inject('$jump')
	const $jumpToTabbar = inject('$jumpToTabbar')

	const loading = ref(false)
	const out = ref(!1) // 订单类型（params参数）
	const page = ref(1)
	const pageSize = ref(10)
	const list = ref([{
		skus: [{}]
	}, {
		skus: [{}]
	}, {
		skus: [{}]
	}, {
		skus: [{}]
	}, {
		skus: [{}]
	}, {
		skus: [{}]
	}])
	const listTotal = ref(0) // 用户订单总数
	const isEmpty = ref(false) // 列表是否为空
	const tabList = ref([{
		name: "接受的",
		out: !1
	}, {
		name: "转出的",
		out: 1
	}]) // 顶部tabs
	const tabCurrentType = ref(0) // 选中tab的索引
	const coinName= ref('')
	onLoad(options => {
		if (options.type !== undefined) {
			tabCurrentType.value = options.type
			out.value = tabList.value[tabIndex].out
		} else {
			out.value = !1
		}
	})
	const show = ref(false)
	onShow(() => {
		// #ifdef H5
		const pageList = getCurrentPages(); //获取应用页面栈
		const {
			$page
		} = pageList[pageList.length - 1]; //获取当前页面信息
		if ($page.options.type) {
			tabCurrentType.value = $page.options.type
			out.value = tabList.value[tabIndex].out
		}
		// #endif
	})
	onMounted(() => {
		nextTick(() => {
			console.log(tabCurrentType.value)
			handleTabChange(Number(tabCurrentType.value))
			coinName.value = getApp().globalData.coinName
		})
		// handleRefreshList()
	})
	onUnload(() => {
		goUserIndex()
	})
	onReachBottom(() => {
		if (!isEmpty.value && list.value.length >= listTotal.value) {
			uni.stopPullDownRefresh()
		} else {
			++page.value
			handleGetOrderList()
		}
	})
	// 返回顶部
	onPageScroll((e) => {
		returnTopFlag.value = e.scrollTop > 600;
		topLeft.value = e.scrollTop
	})

	/**
	 * 重新加载列表
	 */
	async function handleRefreshList() {
		loading.value = true
		page.value = 1
		list.value = [{}, {}, {}, {}, {}, {}]
		isEmpty.value = false
		await handleGetOrderList()
	}


	/**
	 * 切换tab
	 * @param tabIndex
	 */
	async function handleTabChange(tabIndex) {
		topLeft.value = 0
		if (loading.value) return
		tabCurrentType.value = tabIndex;
		out.value = tabList.value[tabIndex].out
		await handleRefreshList()
	}

	/**
	 * 获取列表数据
	 * @return {Promise<void>}
	 */
	async function handleGetOrderList() {
		$showLoading()
		try {
			const params = {
				page: page.value,
				pageSize: pageSize.value,
				condition: {
					out: out.value,
				}
			}
			const {
				data
			} = await request(API.coinTransferOrder, params, 'POST')
			listTotal.value = data.total
			list.value = list.value.concat(data.list).filter(item => JSON.stringify(item) !== '{}')
			if (list.value.length === 0) {
				isEmpty.value = true
			}
		} finally {
			loading.value = false
			$hideLoading()
		}
	}

	/**
	 * 根据订单状态获取状态label
	 * @param state
	 * @param returnType 是否退款1是
	 * @return {string}
	 */
	function getOrderStatusLabel(state) {
		if (state === 1) return "已拒绝"
		else if (state === 2) return "已确认"
		else if (state === 0) return "待确认"
	}

	/**
	 * 根据订单Item获取按钮信息
	 * @param orderItem
	 * @return *[]
	 */
	function getOrderOptionButtonObj(orderItem) {
		const {
			confirmState
		} = orderItem
		const orderNeedBtnList = [] // 订单应有的btn
		// 取消订单
		if ([0].includes(confirmState)) {
			orderNeedBtnList.push({
				name: '确认',
				className: 'l',
				functionName: 'handleConfirm',
				functionParams: [orderItem]
			})
			orderNeedBtnList.push({
				name: '拒绝',
				className: 'l',
				functionName: 'handleReject',
				functionParams: [orderItem]
			})
		}
		return orderNeedBtnList
	}

	const functionList = {
		handleConfirm: handleConfirm,
		handleReject: handleReject,
	}

	/**
	 * 处理订单btn事件
	 * @param buttonItem 由getOrderOptionButtonObj生成的item项
	 */
	function handleOrderOptionButtonEvent(buttonItem) {
		const {
			functionName,
			functionParams
		} = buttonItem
		if (functionList[functionName]) {
			functionList[functionName](...functionParams)
		} else {
			throw new Error(`${ buttonItem.name }的function在本VM中不存在`)
		}
	}

	/**
	 * 确认
	 * @param orderItem
	 */
	function handleConfirm(orderItem) {
		const modalOptions = {
			title: '温馨提示',
			content: '正在确认来自好友转赠？',
			confirmText: '接收',
			cancelText: '点错了',
			success: ({
				confirm
			}) => {
				confirm ? handleDoConfirm(orderItem, 2) : undefined
			}
		}
		uni.showModal(modalOptions)
	}


	/**
	 * 确定取消订单
	 * @param orderItem
	 * @return {Promise<void>}
	 */
	async function handleDoConfirm(orderItem, state) {
		$showLoading()
		try {
			await request(API.coinTransferConfrim, {
				id: orderItem.id,
				state: state
			}, 'POST')
			await handleRefreshList()
			uni.showToast({
				icon: 'none',
				title: '取消成功'
			})
		} finally {
			$hideLoading()
		}
	}

	/**
	 * 确认收货
	 * @param orderItem
	 */
	function handleReject(orderItem) {
		const modalOptions = {
			title: '温馨提示',
			content: '确认拒绝来自好友的转赠',
			confirmText: '不用了',
			cancelText: '点错了',
			success: ({
				confirm
			}) => {
				confirm ? handleDoConfirm(orderItem, 1) : undefined
			}
		}
		uni.showModal(modalOptions)
	}

	/**
	 * 去用户中心
	 */
	function goUserIndex() {
		$jumpToTabbar('/pages/tabbar/user/index')
	}
</script>

<style lang="scss" scoped>
	@import "../../style/images";

	.tabs {
		position: relative;
		z-index: 999;
	}

	page {
		width: 100%;
		height: 100%;
		background: #f6f6f6;
	}

	.nav-box-box {
		height: 88rpx;
		background: #f6f6f6;
		white-space: nowrap;
		position: fixed;
		top: 0;
		left: 0;
		width: 100%;
		z-index: 10;
	}

	.nav-box-box .item {
		display: inline-view;
		padding: 0 30rpx;
		box-sizing: border-box;
		height: 88rpx;
		text-align: center;
		line-height: 88rpx;
		font-size: 30rpx;
		color: #666;
		font-weight: 500;
	}

	.nav-box-box .item.active text {
		display: inline-view;
		color: #ff7911;
		box-sizing: border-box;
		height: 88rpx;
		border-bottom: 2px solid #ff7911;
	}

	.order-list-box {
		padding: 20rpx 30rpx 0;
		box-sizing: border-box;
	}

	.order-list-box .item {
		margin-bottom: 20rpx;
		background: #fff;
		border-radius: 10rpx;
		min-height: 500rpx;
	}

	.order-list-top {
		height: 96rpx;
		padding: 0 30rpx;
		box-sizing: border-box;
		display: flex;
		flex-direction: row;
		align-items: center;
		justify-content: space-between;
		border-bottom: 1px solid #eee;
	}

	.top-l {
		display: flex;
		flex-direction: row;
		align-items: center;
		min-width: 200rpx;
		min-height: 44rpx;
	}

	.shop-img {
		width: 36rpx;
		height: 36rpx;
		margin-right: 10rpx;
	}

	.shop-name {
		font-size: 30rpx;
		color: #333;
		font-weight: bold;
	}

	.arrow-img {
		margin-left: 15rpx;
		width: 25rpx;
		height: 25rpx;
	}

	.order-status {
		font-size: 32upx;
		color: #C5AA7B;
		font-weight: 400;
		min-width: 130rpx;
		min-height: 44rpx;
	}

	.order-info-box {
		padding: 0 30upx;
		box-sizing: border-box;

		.btnBox {
			width: 100%;
			justify-content: flex-end;

			.delIcon {
				width: 40rpx;
				height: 40rpx;
				background: $delListOrder no-repeat center center;
				background-size: contain;
			}
		}

		.flexSpBetween {
			justify-content: space-between;
		}
	}

	.order-info {
		border-bottom: 1px solid #eee;
	}

	.order-info-item {
		display: flex;
		flex-direction: row;
		padding: 20upx 0;
	}

	.product-img {
		width: 180upx;
		height: 180upx;
		margin-right: 30upx;
	}

	.info-box {
		flex: 1;
		display: flex;
		flex-direction: column;
		justify-content: space-between;
	}

	.name-box {
		min-height: 60rpx;
		min-width: 200rpx;

		.product-name {
			font-size: 26upx;
			color: #333;
			height: 68upx;
			line-height: 34upx;
			display: -webkit-box;
			overflow: hidden;
			text-overflow: ellipsis;
			word-break: break-all;
			-webkit-box-orient: vertical;
			-webkit-line-clamp: 2;
		}
	}

	.price-sku-box {
		display: flex;
		flex-direction: row;
		justify-content: space-between;

		.box-h {
			min-width: 140rpx;
			min-height: 40rpx;
		}
	}

	.product-sku {
		font-size: 24upx;
		color: #999;
		min-height: 34rpx;
		min-width: 150rpx;
	}

	.product-price {
		font-size: 28upx;
		color: #333;
		font-weight: 400;
	}

	.product-price .fuhao {
		font-size: 28upx;
	}

	.product-num {
		display: inline-view;
		font-size: 28upx;
		margin-left: 20upx;
		color: #999;
	}

	.total-price-box {
		font-size: 26upx;
		color: #333;
		text-align: right;
		padding: 30upx 0;

		.skeleton-box {
			display: inline-block;
			min-height: 50rpx;
			min-width: 400rpx;
		}
	}

	.order-btn-box {
		padding: 20upx 0;
		display: flex;
		flex-direction: row;
		justify-content: flex-end;
		min-width: 190rpx;
		min-height: 60rpx;
	}

	.order-btn-box .btn {
		display: inline-view;
		width: 150upx;
		height: 56upx;
		text-align: center;
		line-height: 56upx;
		font-size: 26upx;
		color: #333;
		margin-left: 20upx;
	}

	.evaluate {
		height: 56upx;
		text-align: center;
		line-height: 56upx;
		font-size: 26upx;
		padding: 0 30upx;
		color: #C5AA7B;
		background: #333333;
	}

	.evaluate2 {
		height: 56upx;
		text-align: center;
		line-height: 56upx;
		font-size: 26upx;
		padding: 0 30upx;
		background: #333333;
		color: #C5AA7B;
	}

	.order-btn-box .btn.l {
		border: 2rpx solid #333333;
		color: #333;
	}

	.order-btn-box .btn.r {
		border: 2rpx solid #C5AA7B;
		color: #C5AA7B;
	}

	.emptyOrder-box {
		margin-top: 70upx;

		.emptyOrder-img {
			margin-top: 30%;
			width: 216upx;
			height: 152upx;
		}
	}

	.Put-box1 {
		.btn {
			text-align: center;
			margin-top: 40rpx;
			border: 2rpx solid #333333;
			height: 80rpx;
			line-height: 80rpx;
			width: 240rpx;
			color: #333333;
		}

		.submit {
			background-color: #333333;
			color: #FFEBC4;
		}
	}

	.pay-list-content {
		width: 100%;
		padding: 60rpx 30rpx 20rpx 30rpx;
		box-sizing: border-box;
		display: flex;
		flex-direction: column;
		align-items: center;

		cashire-list {
			width: 100% !important;
		}

		.pay-confirm-btn {
			width: 80%;
			height: 88rpx;
			margin-top: 15rpx;
			border-radius: 15rpx;
			color: #fff;
			background-color: #c5aa7b;
			display: flex;
			align-items: center;
			justify-content: center;
		}
	}
</style>
<style scoped>
	.container /deep/ .u-tab-item {
		color: #999999 !important;
	}
	
	.container /deep/ .u-tab-bar {
		background-color: #F3641E !important;
	}
	
</style>